package main

import (
	"encoding/json"
	"fmt"
)

// main
//
//	@Description: 序列化成json串
func main() {
	formatArray()
	formatMap()
	formatStruct()
	formatSlice()
}

// formatArray
//
//	@Description: 序列化数组
func formatArray() {
	fmt.Println("------------序列化数组------------")

	var arr [4]string = [4]string{"tom", "jack", "rose", "lucy"}
	jsonArr, _ := json.Marshal(arr)
	fmt.Println(string(jsonArr))

	var studentArr [3]Student
	studentArr[0] = Student{Name: "tom", Age: 18, Addr: "beijing"}
	studentArr[1] = Student{Name: "rose", Age: 19, Addr: "nk"}
	studentArr[2] = Student{Name: "lucy", Age: 20, Addr: "shanghai"}
	jsonStu, err := json.Marshal(studentArr)
	if err != nil {
		fmt.Println("json marshal err=-", err)
		return
	}
	fmt.Println(string(jsonStu))

}

func formatMap() {
	fmt.Println("------------formatMap------------")

	var m1 map[int]string = make(map[int]string)
	m1[1] = "zhangsan"
	m1[2] = "lisi"
	m1[3] = "wangwu"
	jsonSlice, err := json.Marshal(m1)
	if err != nil {
		fmt.Println("json marshal err=-", err)
		return
	}
	fmt.Println(string(jsonSlice))

	var studentMap map[string]Student = make(map[string]Student)
	studentMap["001"] = Student{
		Name: "jack", Age: 20, Addr: "chongqing",
	}
	studentMap["002"] = Student{
		Name: "rose", Age: 19, Addr: "uk",
	}
	marshal, err := json.Marshal(studentMap)
	if err != nil {
		fmt.Println("json marshal err=-", err)
		return
	}
	fmt.Println(string(marshal))

	//k-string类型 v-为任意类型
	var intMap map[string]interface{} = make(map[string]interface{})
	intMap["no-001"] = "my name is tom"
	intMap["no-002"] = 55.0
	intMap["no-003"] = studentMap
	marshal01, err := json.Marshal(intMap)
	if err != nil {
		fmt.Println("json marshal err=-", err)
		return
	}
	fmt.Println(string(marshal01))
}

// formatStruct
//
//	@Description: json marshal
func formatStruct() {
	fmt.Println("------------formatStruct------------")
	var st Student = Student{
		Name: "admin",
		Addr: "重庆",
		Age:  20,
	}
	jsonSlice, err := json.Marshal(st)
	if err != nil {
		fmt.Println("json marshal err=-", err)
		return
	}
	fmt.Println(string(jsonSlice)) //{"name":"admin","age":20,"addr":"重庆"}
}

func formatSlice() {
	fmt.Println("------------formatSlice------------")
	var slic []interface{} = make([]interface{}, 0)
	slic = append(slic, "tom")
	slic = append(slic, 20)
	slic = append(slic, Student{"tom", 20, "beijing"})
	jsonStr, err := json.Marshal(slic)
	if err != nil {
		fmt.Println("format err=", err)
		return
	}
	fmt.Println(string(jsonStr))

	var studentList []Student = make([]Student, 0)
	studentList = append(studentList, Student{"tom", 11, "beijing"})
	studentList = append(studentList, Student{"jack", 13, "cq"})
	studentList = append(studentList, Student{"rose", 18, "nanjing"})
	marshal, err := json.Marshal(studentList)
	if err != nil {
		fmt.Println("format err=", err)
		return
	}
	fmt.Println(string(marshal))

}

type Student struct {
	Name string `json:"Name"`
	Age  int    `json:"AGE"`
	Addr string `json:"addr"`
}
